package com.sumainfor.common.util;

import com.alibaba.fastjson.JSONObject;
import com.sumainfor.common.entity.SysUserVo;
import com.sumainfor.common.entity.WxUserEntity;
import com.sumainfor.common.exception.LoginFailureException;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Author PuaChen
 * @Create 2018-11-03 10:52
 */
@Log4j2
public class ContextUtils {

    public static final ThreadLocal<Map<String, Object>> THREAD_LOCAL = new ThreadLocal<>();
    public static final String USERKEY = "userKey";
    public static final String HEAD_TYPE = "User_Type";

    public static void setUser(String userJson, Class cls, Integer code) {
        if (StringUtils.isBlank(userJson) || code == null || cls == null) {
            throw new RuntimeException("Invalid Params");
        }
        LinkedHashMap<String, Object> map = new LinkedHashMap<>();

        Object userVo = JSONObject.parseObject(userJson, cls);

        map.put(USERKEY, userVo);
        map.put(HEAD_TYPE, code);
        THREAD_LOCAL.set(map);
    }

    /**
     * 获得 类型
     *
     * @return
     */
    public static Integer getHeadType() {
        Map<String, Object> map = THREAD_LOCAL.get();
        if (MapUtils.isEmpty(map)) {
            log.error("获得 HeadType 类型出错");
            throw new RuntimeException("Invalid HeadType");
        }
        return MapUtils.getInteger(map, HEAD_TYPE);
    }

    public static void setHeadType(Integer type) {
        Map<String, Object> map = THREAD_LOCAL.get();
        if (MapUtils.isEmpty(map)) {
            map = new LinkedHashMap<>();
        }
        map.put(HEAD_TYPE, type);
        THREAD_LOCAL.set(map);
    }

    public static String getUserId() {
        Map<String, Object> map = THREAD_LOCAL.get();
        if (MapUtils.isEmpty(map)) {
            throw new LoginFailureException("请先登录");
        }
        return String.valueOf(((SysUserVo) map.get(USERKEY)).getUserId());
    }

    public static SysUserVo getSysUser() {
        Map<String, Object> map = THREAD_LOCAL.get();
        if (MapUtils.isEmpty(map)) {
            throw new LoginFailureException("请先登录");
        }
        return (SysUserVo) map.get(USERKEY);
    }

    public static WxUserEntity getWxInfo() {
        Map<String, Object> map = THREAD_LOCAL.get();
        if (MapUtils.isEmpty(map)) {
            log.error("Invalid Wx User");
            throw new LoginFailureException("请先登录");
        }
        Object o = map.get(USERKEY);
        if (o == null) {
            log.error("Invalid Wx User");
            throw new LoginFailureException("请先登录");
        }
        return (WxUserEntity) o;
    }

    public static void close() {
        THREAD_LOCAL.remove();
    }
}
